package com.ruoyi.system.chat.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.chat.exception.*;
import com.ruoyi.common.sens.Trie;
import com.ruoyi.system.chat.chatqwen.ChatQwenService;
import com.ruoyi.system.chat.chatqwen.entity.ChatRequestEntity;
import com.ruoyi.system.chat.entity.AiResponseEntity;
import com.ruoyi.system.chat.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Service
@Slf4j
public class ChatServiceWrapper implements ChatService {

    @Autowired
    private ChatQwenService chatQwenService;

    private Trie trie;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public AiResponseEntity chat(ChatRequestEntity chatRequestEntity,
                                 HttpServletRequest request, HttpServletResponse response)
            throws IOException,
            BalanceInsufficientException, BalanceDeductException,
            ChatException,
            ChatConcurrentException,
            SensitiveWordsException {
        // 敏感词检测
        if (trie != null) {
            List<ChatRequestEntity.Message> messages = chatRequestEntity.getMessages();
            if (messages.isEmpty()) {
                throw new IllegalArgumentException("message size is empty");
            }
            ChatRequestEntity.Message message = messages.get(messages.size() - 1);
            if (message.getContent() == null || message.getContent().toString().length() == 0) {
                throw new IllegalArgumentException("the latest message content is empty");
            }
            List<Trie.FindResult> findResults = trie.find(message.getContent().toString());
            if (!findResults.isEmpty()) {
                String replaced = trie.replaceWith(message.getContent().toString(), findResults);
                throw new SensitiveWordsException(replaced);
            }
        }
        AiResponseEntity responseEntity = null;
        try {
            log.info("==========通义千问大模型=========");
            responseEntity = chatQwenService.chat(chatRequestEntity, request, response);
            log.info("responseEntity.isSuccess()==============={}",responseEntity.isSuccess());
            if (!responseEntity.isSuccess()) {
                throw new ChatException("聊天异常");
            }
            if (chatRequestEntity.getStream()!= null) {
                String responseJson = objectMapper.writeValueAsString(responseEntity);
                log.info("responseJson:{}", responseJson);
            }

            return responseEntity;
        } catch (Exception e) {
            try {
                // 如果失败，那么应该额度恢复
//                deductService.rollback(deductResult.getBalanceEntity(), balanceRecordEntity, e);
            } catch (Exception e2) {
                log.info("deductService.rollback failed: {}", e2.getMessage(), e2);
            }
            throw e;
        }
    }

}
